/*
 * Copyright 2012 Marsrutai.lt
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package lt.marsrutai.mobile.android.activity.intent;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;

public class IntentHolder {

    protected Intent intent;

    public IntentHolder(Activity sourceActivity, Class<?> targetActivityClass) {
        intent = new Intent(sourceActivity, targetActivityClass);
    }

    public IntentHolder(Intent intent) {
        this.intent = intent;
    }

    public IntentHolder(Bundle bundle) {
        this.intent = new Intent();
        this.intent.putExtras(bundle);
    }

    public IntentHolder(String broadcastAction) {
        this.intent = new Intent(broadcastAction);
    }

    public Intent getIntent() {
        return intent;
    }
    
    @SuppressWarnings("unchecked")
    public <T extends Parcelable> void setCollection(String key, Collection<T> collection, Class<T> clazz) {
        if (collection != null) {
            intent.putExtra(key, collection.toArray((T[]) Array.newInstance(clazz, collection.size())));
        }
    }
    
    public <T extends Parcelable> void setCollection(String key, T[] collection) {
        if (collection != null) {
            intent.putExtra(key, collection);
        }
    }
    
    @SuppressWarnings("unchecked")
    public <T extends Parcelable> List<T> getList(String key) {
        Parcelable[] parcelables = intent.getParcelableArrayExtra(key);

        if (parcelables == null) {
            return null;
        }

        List<T> result = new ArrayList<T>();
        for (int i = 0; i < parcelables.length; i++) {
            result.add((T) parcelables[i]);
        }
        return result;
    }
    
    @SuppressWarnings("unchecked")
    public <T extends Parcelable> T[] getArray(String key, Class<T> clazz) {
        List<T> list = getList(key);

        return list == null ? null : list.toArray((T[]) Array.newInstance(clazz, list.size()));
    }
}
